package cn.nfwx.tv.wxapi;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;

import org.greenrobot.eventbus.EventBus;

import cn.nfwx.tv.base.NFWXApplication;
import cn.nfwx.tv.callback.ResponseCallback;
import cn.nfwx.tv.callback.UserCallBack;
import cn.nfwx.tv.conts.Constants;
import cn.nfwx.tv.events.BindPhoneEvents;
import cn.nfwx.tv.events.WxBindPhoneEvents;
import cn.nfwx.tv.helper.AccountHelper;
import cn.nfwx.tv.helper.DialogFragmentHelper;
import cn.nfwx.tv.manager.UserManager;
import cn.nfwx.tv.model.User;
import cn.nfwx.tv.model.UserModel;
import cn.nfwx.tv.util.SharePrefUtil;
import cn.nfwx.tv.util.ToastUtil;

/**
 * Created by zhouzechao on 2017/11/28.
 */

public class WXEntryActivity extends FragmentActivity implements IWXAPIEventHandler {
    private IWXAPI api;
    private static final int RETURN_MSG_TYPE_LOGIN = 1;
    private static final int RETURN_MSG_TYPE_SHARE = 2;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        api = ((NFWXApplication) getApplication()).getIwxapi();
        api.handleIntent(getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }


    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp resp) {
        int result = 0;
        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                switch (resp.getType()) {
                    case RETURN_MSG_TYPE_LOGIN://登录
                        String code = ((SendAuth.Resp) resp).code;
                        Log.d("code", code);
                        if (AccountHelper.getInstance().getLiveStats() == Constants.STATS_P2P) {
                            UserManager.loginWeChat(this, code, new UserCallBack() {
                                @Override
                                public void onSuccess(final UserModel userModel) {
                                    WXEntryActivity.this.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Log.d("loginWeChat", "登录成功");
                                            SharePrefUtil.saveWechatUser(WXEntryActivity.this, userModel);//缓存用户数据
                                            EventBus.getDefault().post(new BindPhoneEvents(userModel));
                                            finish();

                                        }
                                    });
                                }

                                @Override
                                public void onFail(String code, final String response) {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Log.d("loginWeChat", "==" + response);
                                            Toast.makeText(WXEntryActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                                            finish();

                                        }
                                    });
                                }

                                @Override
                                public void onComplete() {
                                    super.onComplete();
                                    finish();
                                }
                            });
                        } else if (AccountHelper.getInstance().getLiveStats() == Constants.STATS_QPOP) {
                            DialogFragmentHelper.showLoadingDialog(getSupportFragmentManager());
                            UserManager.requestIjkCheckWX(this, code, new ResponseCallback<JSONObject>() {
                                @Override
                                public void onSuccess(String requestTag, final JSONObject wxUser) {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                                            finish();
                                            User user = JSON.parseObject(wxUser.toJSONString(), new TypeReference<User>() {
                                            }.getType());
                                            EventBus.getDefault().post(new WxBindPhoneEvents(user));
                                        }
                                    });
                                }

                                @Override
                                public void onFailure(String requestTag, String message) {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                                            ToastUtil.show(WXEntryActivity.this, "认证超时");
                                            finish();
                                        }
                                    });
                                }
                            });
                        }
                        break;
                    case RETURN_MSG_TYPE_SHARE://分享
                        Toast.makeText(this, "分享成功", Toast.LENGTH_SHORT).show();
                        finish();
                        break;
                }
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                if (RETURN_MSG_TYPE_SHARE == resp.getType()) {
                    Toast.makeText(this, "取消分享", Toast.LENGTH_SHORT).show();
                } else if (RETURN_MSG_TYPE_LOGIN == resp.getType()) {
                    Toast.makeText(this, "取消登录", Toast.LENGTH_SHORT).show();
                }
                finish();
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                Toast.makeText(this, "权限限制", Toast.LENGTH_SHORT).show();
                finish();
                break;
            case BaseResp.ErrCode.ERR_UNSUPPORT:
                finish();
                break;
        }
        Toast.makeText(this, result, Toast.LENGTH_LONG).show();
    }
}
